module.exports = function($scope, $resource, $modal, $stateParams, $timeout, Excel, toaster, getDate){
    var temp = {};

    //加载快捷查询固定项
    $scope.getFixed = function(temp, rule){
        $resource('/api/as/tc/countfixed/getFixedList', {}, {}).save({}, function (res) {
            if (res.errcode === 0) {
                $scope.fixedList = res.data;
            } else {
                $scope.fixedList = [];
            }
            $scope.fixedList.unshift({'title': temp.str1, 'context': temp.str2});
            angular.forEach($scope.fixedList, function(item){
                temp[item.context] = item.title;
            });
            $scope.fromData.group_rule = rule;
            $scope.fromData.searchType = true;
        });
    }

    init();
    function init(){
        $scope.fromData = {
            'loading': false,
            'searchType': true,
            'today': getDate(new Date()),
            'selectedList': [], //显示结果使用,
            'total': {}
        };
        $scope.resultList = [
            {'label': '日期', 'value': 'every_date', 'check': false, 'width': '100', 'align': 'text-center', 'more': 1, 'showCode': true},
            {'label': '景区', 'value': 'place_code', 'check': false, 'width': '100', 'align': 'text-center', 'more': 'place_name', 'showCode': false},
            {'label': '票种', 'value': 'ticket_type', 'check': false, 'width': '120', 'align': 'text-center', 'more': 'ticket_name', 'showCode': false},
            {'label': '产品类型', 'value': 'sale_category', 'check': false, 'width': '150', 'align': 'text-center', 'more': 'sale_category_name', 'showCode': true},
            {'label': '产品', 'value': 'sale_code', 'check': false, 'width': '200', 'align': 'text-left', 'more': 'sale_name', 'showCode': true},
            {'label': '供应商', 'value': 'up_company_code', 'check': false, 'width': '120', 'align': 'text-left', 'more': 'up_company_name', 'showCode': true},
            {'label': '分销商', 'value': 'down_company_code', 'check': false, 'width': '120', 'align': 'text-left', 'more': 'down_company_name', 'showCode': true},
            {'label': '销售账号', 'value': 'operation_login_name', 'check': false, 'width': '120', 'align': 'text-left', 'more': 1, 'showCode': true},
            {'label': '支付类型', 'value': 'payment_type', 'check': false, 'width': '120', 'align': 'text-center', 'more': 'payment_type_name', 'showCode': false},
            {'label': '售卖渠道', 'value': 'channel_list_code', 'check': false, 'width': '150', 'align': 'text-center', 'more': 1, 'showCode': true},
            {'label': '订单来源', 'value': 'from_app_id', 'check': false, 'width': '120', 'align': 'text-center', 'more': 'from_app_name', 'showCode': false},
            {'label': '单价', 'value': 'unit_price', 'check': false, 'width': '80', 'align': 'text-center', 'more': 1, 'showCode': true},
            {'label': '补贴单价', 'value': 'platform_order_actual_subsidy', 'check': false, 'width': '80', 'align': 'text-center', 'more': 1, 'showCode': true},
        ];
        $scope.resultShow = [
            {'label': '产品类型', 'value': 'sale_category', 'more': 'sale_category_name'},
            {'label': '供应商', 'value': 'up_company_code',  'more': 'up_company_name'},
            {'label': '分销商', 'value': 'down_company_code', 'more': 'down_company_name'},
            {'label': '支付类型', 'value': 'payment_type', 'more': 'payment_type_name'},
            {'label': '订单来源', 'value': 'from_app_id', 'more': 'from_app_name'},
            {'label': '景区', 'value': 'place_code', 'more': 'place_name'},
            {'label': '票种', 'value': 'ticket_type', 'more': 'ticket_name'}
        ];
        $scope.filters = {
            'sale_category' : {},
            'up_company_code' : {},
            'down_company_code' : {},
            'payment_type' : {},
            'from_app_id' : {},
            'place_code' : {},
            'ticket_type' : {}
        };
        
        if($stateParams.type == 'buy'){
            $scope.fromData.shown = true;
            $scope.resultList.push({
                'label': '出游日期', 
                'value': 'tour_date', 
                'check': false, 
                'width': '80', 
                'align': 'text-center', 
                'more': 1, 
                'showCode': true
            });
            $scope.fromData.url = '/api/as/tc/ticketorder/newsalestatisticslist';
            temp.str1 = '默认预定报表';
            temp.str2 = 'sale_code,up_company_code,down_company_code';
            $scope.getFixed(temp, 'sale_code,up_company_code,down_company_code');
        } else if($stateParams.type == 'used'){
            $scope.fromData.shown = false;
            $scope.resultList.push({
                'label': '设备', 
                'value': 'device', 
                'check': false, 
                'width': '80', 
                'align': 'text-center', 
                'more': 'device_remarks', 
                'showCode': true
            });
            $scope.fromData.url = '/api/as/tc/ticketorder/newusedstatisticslist';
            temp.str1 = '默认使用报表';
            temp.str2 = 'ticket_type,sale_code,up_company_code,down_company_code';
            $scope.getFixed(temp, 'ticket_type,sale_code,up_company_code,down_company_code');
        }
        //下载的报表文件名
        $scope.excelTitle = temp.str1 + $scope.fromData.today;
        $scope.date = {
            'lable': $scope.fromData.today,
            'opened': false
        };
        $scope.date1 = {
            'lable': $scope.fromData.today,
            'opened': false
        };
    }

    //查询数据
    $scope.load = function (){
        var group_rule = '';
        $scope.fromData.selectedList = [];
        if($scope.fromData.searchType){
            group_rule = $scope.fromData.group_rule;
            angular.forEach($scope.resultList, function(item){
                if(group_rule.indexOf(item.value) != -1){
                    $scope.fromData.selectedList.push(item);
                }
            });
            //更新下载的报表文件名
            $scope.excelTitle = temp[group_rule] + $scope.fromData.today;
        } else {
            angular.forEach($scope.resultList, function(item){
                if(item.check){
                    group_rule += item.value + ',';
                    $scope.fromData.selectedList.push(item);
                }
            });
            group_rule = group_rule.substring(0, group_rule.length - 1);
            //更新下载的报表文件名
            $scope.excelTitle = '自定义报表' + $scope.fromData.today;
        }
        if(!group_rule){
            toaster.warning({'title': '', 'body': '请选择想要查询的结果列'});
            return;
        }
        var para = {
            'start_time' : getDate($scope.date.lable),
            'end_time' : getDate($scope.date1.lable),
            'scope': $stateParams.scope,
            'group_rule': group_rule
        };
        $scope.fromData.start_time = para.start_time;
        $scope.fromData.end_time = para.end_time;
        $scope.fromData.loading = true;
        $scope.fromData.total.price = 0;
        $scope.fromData.total.buy = 0;
        $scope.fromData.total.used = 0;
        $scope.fromData.total.back = 0;
        $scope.fromData.total.subsidy = 0;

        $resource($scope.fromData.url, {}, {}).save(para, function (res) {
            if (res.errcode === 0) {
                $scope.saleList = res.data;
                angular.forEach($scope.saleList, function(item){
                    if(item.sale_category_name){
                        $scope.filters.sale_category[item.sale_category_name] = true;
                    }
                    if(item.up_company_name){
                        $scope.filters.up_company_code[item.up_company_name] = true;
                    }
                    if(item.down_company_name){
                        $scope.filters.down_company_code[item.down_company_name] = true;
                    }
                    if(item.payment_type_name){
                        $scope.filters.payment_type[item.payment_type_name] = true;
                    }
                    if(item.from_app_name){
                        $scope.filters.from_app_id[item.from_app_name] = true;
                    }
                    if(item.place_code){
                        $scope.filters.place_code[item.place_name] = true;
                    }
                    if(item.ticket_name){
                        $scope.filters.ticket_type[item.ticket_name] = true;
                    }
                    item.show = true;
                    item.row_key = '';
                    item.row_not_show_str ='';
                    angular.forEach($scope.resultShow, function(result){
                        item.row_key += '#' + item[result.more] + '#' + result.value + ',';
                    });
                    $scope.fromData.total.price += item.down_price || 0;
                    $scope.fromData.total.buy += item.buy;
                    $scope.fromData.total.used += item.used;
                    $scope.fromData.total.back += item.back;
                    $scope.fromData.total.subsidy += item.total_platform_order_actual_subsidy || 0;
                });
                $scope.fromData.loading = false;
            } else {
                toaster.error({title: '', body: '查询统计失败'});
            }
        });
    };

    //删除搜索固定项按钮
    $scope.delete = function(index,id){
        if(confirm('确认删除此固定搜索结果模板吗?')){
            $resource('/api/as/tc/countfixed/delete', {}, {}).save({'id': id}, function (res) {
                if (res.errcode === 0) {
                    toaster.success({'title': '', 'body': '删除成功'});
                    $scope.fixedList.splice(index, 1);
                } else {
                    toaster.error({'title': '', 'body': '删除失败, 请重试'});
                }
            });
        }
    }

    //添加固定搜索项
    $scope.addFixed = function(){
        if($scope.fixedList.length > 10){
            toaster.warning({'title': '', 'body': '最多添加10个自定义搜索结果项'});
            return;
        }
        var group_rule = '';
        angular.forEach($scope.resultList, function(item){
            if(item.check){
                group_rule += item.value + ',';
            }
        });
        if(!group_rule){
            toaster.warning({'title': '', 'body': '请选择结果列'});
            return;
        }
        var modalInstance = $modal.open({
			template: require('../views/addFixedName.html'),
			controller: 'addFixedName',
			size: 'lg',
			resolve: {
				group_rule: function () {
					return group_rule.substring(0, group_rule.length-1);
				}
			}
		});
		//关闭模态框刷新页面
		modalInstance.result.then(function(result) {
            $scope.getFixed(temp, result);
		});
    }

    $scope.setFixed = function(){
        angular.forEach($scope.resultList, function(item){
            item.check = false;
        });
        $scope.fromData.searchType = false;
    }

    //筛选过滤条件
    $scope.filterType = function(key, value, filters, aa){
        $scope.fromData.total.price = 0;
        $scope.fromData.total.buy = 0;
        $scope.fromData.total.used = 0;
        $scope.fromData.total.back = 0;
        filters[key] = !value;
        angular.forEach($scope.saleList, function(item){
            if(item.row_key.indexOf('#' + key + '#' + aa.value) != -1){
                if(value){
                    item.row_not_show_str += '#' + key + '#' + aa.value + ',';
                    item.show = !value;
                } else {
                    item.row_not_show_str = item.row_not_show_str.replace('#'+ key + '#' + aa.value + ',', '');
                    if(!item.row_not_show_str){
                        item.show = !value;
                    }
                }
            }
            if(item.show){
                $scope.fromData.total.price += item.down_price;
                $scope.fromData.total.buy += item.buy;
                $scope.fromData.total.used += item.used;
                $scope.fromData.total.back += item.back;
            }
        });
        for(var k in filters){
            if(!filters[k]){
                aa.isfilter = true;
                break;
            }
            aa.isfilter = false;
        }
    }

    //打开日历空间,选择时间
    $scope.dateOpen = function ($event, item) {
        $event.preventDefault();
        $event.stopPropagation();
        item.opened = true;
    };

    $scope.setStyle = function(item){
        return {"min-width": item.width + 'px'};
    }

    $scope.dropdownMenu = function(item, list){
        if(!item.open){
            angular.forEach(list, function(info){
                info.open = false;
            });
        }
        item.open = !item.open;
    }

    $scope.selectFlag = function(flag, obj, aa){
        for(var k in obj){
            if(obj[k] == flag){
                $scope.filterType(k,flag,obj,aa);
            }
        }
    }


    //导出excel文件-------------------start-------------
    $scope.downloadExl = function(){
        if(!$scope.saleList || $scope.saleList.length == 0){
            toaster.warning({'title': '', 'body': '请查询统计数据后再导出'});
            return;
        }
        var exportList = exportData();
        
        const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };  //这里的数据是用来定义导出的格式类型
        const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };
        wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(exportList);
        var blob = new Blob([str2binary(XLSX.write(wb, wopts))], {type: 'application/octet-stream' });

        var dlink = document.getElementById('dlink');
        dlink.href = URL.createObjectURL(blob);
        dlink.click();
        setTimeout(function () {
            URL.revokeObjectURL(blob); //释放这个object URL
        }, 100);

    };
    //导出excel前的二进制转码
    function str2binary(s) {
        if (typeof ArrayBuffer !== 'undefined') {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        } else {
            var buf = new Array(s.length);
            for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }
    }
    //筛选出页面显示的数据
    function exportData(){
        var exportList = [];
        angular.forEach($scope.saleList, function(item){
            if(item.show){
                var sale = {};
                angular.forEach($scope.fromData.selectedList, function(selected){
                    if(selected.more != 1){
                        sale[selected.label] = item[selected.more] + '(' + item[selected.value] + ')';
                    } else {
                        if(selected.value == 'unit_price'){
                            sale['单价(元)'] = item[selected.value] / 100;
                        } else if(selected.value == 'platform_order_actual_subsidy'){
                            sale['补贴单价'] = item[selected.value] / 100;
                        } else {
                            sale[selected.label] = item[selected.value];
                        }
                    }
                });
                if($scope.fromData.shown){
                    sale['总金额(元)'] = item.down_price / 100;
                    sale['购买数量'] = item.buy;
                    sale['退票数量'] = item.back;
                } else {
                    sale['使用数量'] = item.used;
                }
                sale['补贴总额'] = item.total_platform_order_actual_subsidy / 100;
                exportList.push(sale);
            }
        });
        if($scope.fromData.shown){
            exportList.push({'总金额(元)': $scope.fromData.total.price / 100, 
                            '购买数量':$scope.fromData.total.buy,
                            '退票数量': $scope.fromData.total.back,
                            '补贴总额': $scope.fromData.total.subsidy
                            });
        } else {
            exportList.push({'使用数量': $scope.fromData.total.used,'补贴总额': $scope.fromData.total.subsidy});
        }

        return exportList;
    }

    //导出每行的明细
    $scope.downloadDetail = function(obj){
        if(obj.waiting){
            return;
        }
        obj.waiting = true;
        var para = {
            'detail': '1',
            'start_time': $scope.fromData.start_time,
            'end_time': $scope.fromData.end_time,
        }
        angular.forEach($scope.fromData.selectedList, function(item){
            para[item.value] = obj[item.value] + '';
        });
        $resource($scope.fromData.url, {}, {}).save(para, function (res) {
            if (res.errcode === 0) {
                var exportList = [];
                angular.forEach(res.data, function(item){
                    var sale = {};
                    angular.forEach($scope.fromData.selectedList, function(selected){
                        if(selected.more != 1){
                            sale[selected.label] = obj[selected.more] + '(' + obj[selected.value] + ')';
                        } else {
                            if(selected.value == 'unit_price'){
                                sale['单价(元)'] = obj.unit_price / 100;
                            } else if(selected.value == 'platform_order_actual_subsidy'){
                                sale['补贴单价'] = obj.platform_order_actual_subsidy / 100;
                            } else {
                                sale[selected.label] = item[selected.value];
                            }
                        }
                    });

                    sale['日期'] = obj.every_date;
                    sale['订单编号'] = item.order_code;
                    sale['金额(元)'] = item.down_price / 100;
                    if($scope.fromData.shown){
                        sale['购买数量'] = item.buy;
                        sale['退票数量'] = item.back;
                        sale['订单时间'] = item.order_time;
                        sale['出游日期'] = obj.tour_date;
                    } else {
                        sale['使用数量'] = item.used;
                    }
                    exportList.push(sale);
                });
                if($scope.fromData.shown){
                    exportList.push({'金额(元)': obj.down_price / 100, 
                                    '购买数量': obj.buy,
                                    '退票数量': obj.back
                                    });
                } else {
                    exportList.push({'使用数量': obj.used});
                }
                $scope.downloadExl2(exportList);
            } else {
                toaster.error({title: '', body: '导出数据失败'});
            }
            obj.waiting = false;
        });
    }
    $scope.downloadExl2 = function(exportList){
        const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };  //这里的数据是用来定义导出的格式类型
        const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };
        wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(exportList);
        var blob = new Blob([str2binary(XLSX.write(wb, wopts))], {type: 'application/octet-stream' });

        var tmpa = document.createElement("a");
        tmpa.download = '报表明细' + $scope.fromData.today + '.xlsx';
        tmpa.href = URL.createObjectURL(blob); //绑定a标签
        tmpa.click(); //模拟点击实现下载
        setTimeout(function () { //延时释放
            URL.revokeObjectURL(blob); //用URL.revokeObjectURL()来释放这个object URL
        }, 100);
    }
    //导出excel文件------------------end---------------




    //----以下是页面快捷选择日期按钮-----
    $scope.today = function(){
        var now = new Date();
        $scope.date.lable = getDate(now);
        $scope.date1.lable = $scope.date.lable;
        // $scope.load();
    }

    $scope.yesterday = function(){
        var now = new Date();
        now.setDate(now.getDate() - 1);
        $scope.date.lable = getDate(now);
        $scope.date1.lable = getDate(now);
        // $scope.load();
    }

    $scope.thisWeek = function(){
        var now = new Date();
        $scope.date1.lable = getDate(now);

        var week = now.getDay() - 1;
        week = week == -1 ? 6 : week
        now.setDate(now.getDate() - week);
        $scope.date.lable = getDate(now);
        // $scope.load();
    }

    $scope.lastWeek = function(){
        var now = new Date();
        var week = now.getDay() - 1;
        week = week == -1 ? 6 : week
        now.setDate(now.getDate() - week);
        $scope.date1.lable = getDate(now);

        now.setDate(now.getDate() - 7);
        $scope.date.lable = getDate(now);
        // $scope.load();
    }

    $scope.thisMonth = function(){
        var now = new Date();
        $scope.date1.lable = getDate(now);
        
        now.setDate(1);
        $scope.date.lable = getDate(now);
        // $scope.load();
    }

    $scope.lastMonth = function(){
        var now = new Date();
        now.setDate(0);
        $scope.date1.lable = getDate(now);

        now.setDate(1);
        $scope.date.lable = getDate(now);
        // $scope.load();
    }

};